<template>
  <AiFeatureBase
    title="AI图像生成"
    icon="🎨"
    description="输入文字描述，AI为你创作精美图像"
    :examples="examples"
    :modes="imageModes"
    :quick-actions="quickActions"
    :stats="stats"
    :is-loading="isGenerating"
    support-image
    input-placeholder="描述您想要生成的图像..."
    @send="handleGenerate"
    @select-example="handleSelectExample"
    @select-mode="handleSelectMode"
    @quick-action="handleQuickAction"
    @image-select="handleImageSelect"
  >
    <template #content>
      <!-- 生成历史 -->
      <div class="generation-history">
        <div v-if="generatedImages.length === 0 && !isGenerating" class="empty-state">
          <div class="empty-icon">🎨</div>
          <h3>开始创作</h3>
          <p>输入描述文字，AI将为您生成精美的图像</p>
          
          <!-- 风格预览 -->
          <div class="style-preview-section">
            <h4>选择生成风格：</h4>
            <div class="style-preview-grid">
              <div
                v-for="style in imageStyles"
                :key="style.id"
                :class="['style-preview-item', { active: selectedStyle === style.id }]"
                @click="selectStyle(style)"
              >
                <div class="style-preview-image">{{ style.icon }}</div>
                <span class="style-name">{{ style.name }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 生成中状态 -->
        <div v-if="isGenerating" class="generating-state">
          <div class="generating-animation">
            <div class="paint-brush">🖌️</div>
            <div class="generating-text">
              <h3>AI正在创作中...</h3>
              <p>{{ generatingText }}</p>
              <van-progress :percentage="generatingProgress" stroke-width="8" />
              <div class="generating-tips">
                <p>💡 {{ currentTip }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 图像网格 -->
        <div v-if="generatedImages.length > 0" class="images-grid">
          <div
            v-for="(item, index) in generatedImages"
            :key="index"
            class="image-item"
          >
            <div class="image-wrapper">
              <img
                :src="item.url"
                :alt="item.prompt"
                @click="previewImage(item.url, generatedImages.map(img => img.url))"
                @error="handleImageError(item, index)"
                @load="handleImageLoad(item)"
              />
              <div class="image-overlay">
                <div class="image-actions">
                  <van-button size="mini" type="primary" @click="previewImage(item.url)">
                    预览
                  </van-button>
                  <van-button size="mini" @click="downloadImage(item.url, item.prompt)">
                    下载
                  </van-button>
                  <van-button size="mini" @click="shareImage(item)">
                    分享
                  </van-button>
                  <van-button size="mini" @click="regenerateImage(item.prompt)">
                    重新生成
                  </van-button>
                </div>
              </div>
            </div>
            <div class="image-info">
              <div class="image-prompt">{{ item.prompt }}</div>
              <div class="image-meta">
                <span class="image-style">{{ getStyleName(item.style) }}</span>
                <span class="image-size">{{ item.size }}</span>
                <span class="image-time">{{ formatTime(item.timestamp) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <template #settings>
      <div class="settings-content">
        <div class="setting-group">
          <h4>图像尺寸</h4>
          <van-radio-group v-model="settings.size">
            <van-radio name="512x512">正方形 (512×512)</van-radio>
            <van-radio name="768x512">横向 (768×512)</van-radio>
            <van-radio name="512x768">纵向 (512×768)</van-radio>
            <van-radio name="1024x1024">高清 (1024×1024)</van-radio>
          </van-radio-group>
        </div>

        <div class="setting-group">
          <h4>生成数量</h4>
          <van-stepper v-model="settings.count" min="1" max="4" />
          <p class="setting-desc">一次最多生成4张图片</p>
        </div>

        <div class="setting-group">
          <h4>创意程度</h4>
          <van-slider v-model="settings.creativity" min="0" max="100" />
          <div class="slider-labels">
            <span>保守 ({{ settings.creativity }}%)</span>
            <span>创新</span>
          </div>
        </div>

        <div class="setting-group">
          <h4>图像质量</h4>
          <van-radio-group v-model="settings.quality">
            <van-radio name="standard">标准</van-radio>
            <van-radio name="high">高质量</van-radio>
            <van-radio name="ultra">超高质量</van-radio>
          </van-radio-group>
        </div>

        <div class="setting-group">
          <h4>负面提示词</h4>
          <van-field
            v-model="settings.negativePrompt"
            type="textarea"
            placeholder="描述不想要的元素..."
            rows="2"
            autosize
          />
        </div>

        <div class="setting-group">
          <h4>其他选项</h4>
          <div class="setting-item">
            <van-switch v-model="settings.saveHistory" size="20" />
            <span class="setting-label">保存生成历史</span>
          </div>
          <div class="setting-item">
            <van-switch v-model="settings.autoDownload" size="20" />
            <span class="setting-label">自动下载图片</span>
          </div>
        </div>
      </div>
    </template>
  </AiFeatureBase>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { showToast, showImagePreview } from 'vant'
import AiFeatureBase from '@/components/AiFeatureBase.vue'
import { useAIService } from '@/utils/aiServiceManager'
import { getUserInfo } from '@/utils/auth'

// AI服务
const aiService = useAIService()

// 响应式数据
const generatedImages = ref<any[]>([])
const isGenerating = ref(false)
const generatingText = ref('正在分析您的描述...')
const generatingProgress = ref(0)
const selectedStyle = ref('realistic')
const currentTip = ref('好的提示词能生成更好的图像')

// 设置
const settings = ref({
  size: '512x512',
  count: 1,
  creativity: 70,
  quality: 'high',
  negativePrompt: '',
  saveHistory: true,
  autoDownload: false
})

// 统计数据
const stats = ref([
  { label: '今日生成', value: '8' },
  { label: '成功率', value: '95%' },
  { label: '平均时间', value: '15s' }
])

// 生成模式
const imageModes = ref([
  {
    id: 'realistic',
    name: '写实风格',
    description: '真实感强的图像',
    icon: '📷'
  },
  {
    id: 'artistic',
    name: '艺术风格',
    description: '艺术化的图像',
    icon: '🎨'
  },
  {
    id: 'anime',
    name: '动漫风格',
    description: '日式动漫风格',
    icon: '🎭'
  },
  {
    id: 'cartoon',
    name: '卡通风格',
    description: '可爱的卡通风格',
    icon: '🎪'
  }
])

// 图像风格
const imageStyles = ref([
  { id: 'realistic', name: '写实', icon: '📷' },
  { id: 'artistic', name: '艺术', icon: '🎨' },
  { id: 'anime', name: '动漫', icon: '🎭' },
  { id: 'cartoon', name: '卡通', icon: '🎪' },
  { id: 'abstract', name: '抽象', icon: '🌀' },
  { id: 'vintage', name: '复古', icon: '📼' }
])

// 示例提示词
const examples = ref([
  { text: '一只可爱的小猫在花园里玩耍', icon: '🐱' },
  { text: '未来科技城市的夜景', icon: '🌃' },
  { text: '梦幻森林中的精灵', icon: '🧚' },
  { text: '宇宙中的星云和行星', icon: '🌌' },
  { text: '古代中国的山水画', icon: '🏔️' }
])

// 快速操作
const quickActions = ref([
  { id: 'clear', text: '清空历史', icon: 'delete-o', type: 'default' },
  { id: 'gallery', text: '图片库', icon: 'photo-o', type: 'default' },
  { id: 'batch', text: '批量下载', icon: 'down', type: 'default' }
])

// 生成提示
const generatingTips = [
  '详细的描述能生成更精确的图像',
  '尝试添加风格关键词，如"油画风格"、"水彩画"',
  '描述光线和色彩能让图像更生动',
  '添加情感词汇能让图像更有感染力'
]

// 用户信息
const userInfo = computed(() => getUserInfo())

// 方法
const handleGenerate = async (prompt: string) => {
  if (!prompt.trim() || isGenerating.value) return

  isGenerating.value = true
  generatingProgress.value = 0
  generatingText.value = '正在分析您的描述...'
  currentTip.value = generatingTips[Math.floor(Math.random() * generatingTips.length)]

  // 模拟进度更新
  const progressInterval = setInterval(() => {
    if (generatingProgress.value < 90) {
      generatingProgress.value += Math.random() * 10
      if (generatingProgress.value > 30 && generatingProgress.value < 60) {
        generatingText.value = 'AI正在构思画面...'
      } else if (generatingProgress.value >= 60) {
        generatingText.value = '正在绘制细节...'
      }
    }
  }, 500)

  try {
    const response = await aiService.imageGeneration({
      userId: userInfo.value?.id || 1,
      message: prompt,
      mode: selectedStyle.value,
      options: {
        style: selectedStyle.value,
        size: settings.value.size,
        count: settings.value.count,
        quality: settings.value.quality,
        creativity: settings.value.creativity,
        negativePrompt: settings.value.negativePrompt
      }
    })

    clearInterval(progressInterval)
    generatingProgress.value = 100
    generatingText.value = '生成完成！'

    if (response.success && response.data) {
      const images = Array.isArray(response.data) ? response.data : [response.data]
      
      for (const imageUrl of images) {
        const newImage = {
          url: imageUrl,
          prompt: prompt,
          style: selectedStyle.value,
          size: settings.value.size,
          timestamp: Date.now()
        }
        
        generatedImages.value.unshift(newImage)
        
        if (settings.value.autoDownload) {
          downloadImage(imageUrl, prompt)
        }
      }
      
      showToast(`成功生成${images.length}张图片！`)
    } else {
      throw new Error(response.error || '生成失败')
    }
  } catch (error) {
    clearInterval(progressInterval)
    console.error('图像生成失败:', error)
    showToast('生成失败，请重试')
  } finally {
    setTimeout(() => {
      isGenerating.value = false
      generatingProgress.value = 0
    }, 1000)
  }
}

const handleSelectExample = (example: any) => {
  const text = typeof example === 'string' ? example : example.text
  handleGenerate(text)
}

const handleSelectMode = (mode: any) => {
  selectedStyle.value = mode.id
  showToast(`已切换到${mode.name}`)
}

const handleQuickAction = (action: any) => {
  switch (action.id) {
    case 'clear':
      generatedImages.value = []
      showToast('历史已清空')
      break
    case 'gallery':
      showToast('图片库功能开发中...')
      break
    case 'batch':
      batchDownload()
      break
  }
}

const handleImageSelect = () => {
  showToast('图片上传功能开发中...')
}

const selectStyle = (style: any) => {
  selectedStyle.value = style.id
  showToast(`已选择${style.name}风格`)
}

const previewImage = (url: string, urls?: string[]) => {
  showImagePreview({
    images: urls || [url],
    startPosition: urls ? urls.indexOf(url) : 0
  })
}

const downloadImage = (url: string, prompt: string) => {
  const link = document.createElement('a')
  link.href = url
  link.download = `ai-image-${prompt.slice(0, 20)}-${Date.now()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  showToast('开始下载图片')
}

const shareImage = (item: any) => {
  if (navigator.share) {
    navigator.share({
      title: 'AI生成的图片',
      text: `提示词: ${item.prompt}`,
      url: item.url
    })
  } else {
    navigator.clipboard.writeText(item.url)
    showToast('图片链接已复制到剪贴板')
  }
}

const regenerateImage = (prompt: string) => {
  handleGenerate(prompt)
}

const handleImageError = (item: any, index: number) => {
  console.error('图片加载失败:', item)
  showToast('图片加载失败')
}

const handleImageLoad = (item: any) => {
  console.log('图片加载成功:', item.url)
}

const getStyleName = (styleId: string) => {
  const style = imageStyles.value.find(s => s.id === styleId)
  return style ? style.name : styleId
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const batchDownload = () => {
  if (generatedImages.value.length === 0) {
    showToast('没有可下载的图片')
    return
  }
  
  generatedImages.value.forEach((item, index) => {
    setTimeout(() => {
      downloadImage(item.url, item.prompt)
    }, index * 500) // 延迟下载避免浏览器阻止
  })
  
  showToast(`开始批量下载${generatedImages.value.length}张图片`)
}

// 生命周期
onMounted(async () => {
  // 加载用户统计数据
  try {
    const userStats = await aiService.getUserStats(userInfo.value?.id || 1)
    if (userStats.imageGeneration) {
      stats.value = [
        { label: '今日生成', value: userStats.imageGeneration.todayCount || '0' },
        { label: '成功率', value: `${userStats.imageGeneration.successRate || 95}%` },
        { label: '平均时间', value: `${userStats.imageGeneration.avgTime || 15}s` }
      ]
    }
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
})
</script>

<style scoped>
.generation-history {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 20px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 8px 0;
}

.empty-state p {
  font-size: 14px;
  margin: 0 0 32px 0;
  line-height: 1.5;
}

.style-preview-section h4 {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 16px 0;
}

.style-preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  max-width: 300px;
  margin: 0 auto;
}

.style-preview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background: #f8fafc;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 13px;
}

.style-preview-item:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}

.style-preview-item.active {
  border-color: #3b82f6;
  background: #dbeafe;
}

.style-preview-image {
  font-size: 24px;
}

.generating-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  padding: 40px 20px;
}

.generating-animation {
  text-align: center;
  max-width: 300px;
}

.paint-brush {
  font-size: 48px;
  margin-bottom: 16px;
  animation: paint 2s ease-in-out infinite;
}

@keyframes paint {
  0%, 100% { transform: rotate(-10deg); }
  50% { transform: rotate(10deg); }
}

.generating-text h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 8px 0;
}

.generating-text p {
  font-size: 14px;
  color: #64748b;
  margin: 0 0 16px 0;
}

.generating-tips {
  margin-top: 16px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.generating-tips p {
  font-size: 13px;
  color: #1e40af;
  margin: 0;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 16px 0;
}

.image-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.image-item:hover {
  transform: translateY(-2px);
}

.image-wrapper {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.image-wrapper:hover img {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

.image-info {
  padding: 12px;
}

.image-prompt {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.image-meta {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #64748b;
  flex-wrap: wrap;
}

.image-meta span {
  background: #f1f5f9;
  padding: 2px 6px;
  border-radius: 4px;
}

.settings-content {
  padding: 0;
}

.setting-group {
  margin-bottom: 24px;
}

.setting-group h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 12px 0;
}

.setting-desc {
  font-size: 12px;
  color: #64748b;
  margin: 4px 0 0 0;
}

.slider-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #64748b;
  margin-top: 4px;
}

.setting-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.setting-label {
  margin-left: 8px;
  font-size: 14px;
  color: #374151;
}

.van-radio,
.van-checkbox {
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .images-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }
  
  .style-preview-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .image-actions {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
